package com.quectel.cms.controller.grid;


import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.controller.grid.helper.GridHelper;
import com.quectel.cms.util.SessionHolder;
import com.quectel.constant.core.grid.GridConstant;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.grid.dto.GridNoticeDto;
import com.quectel.core.module.grid.dto.GridRegionInfoDto;
import com.quectel.core.module.grid.service.GridNoticeRelationService;
import com.quectel.core.module.grid.service.GridNoticeService;
import com.quectel.core.module.grid.service.GridService;
import com.quectel.core.module.group.service.SysGroupRegionService;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.sys.module.sys.service.SysGroupService;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/02/03 16:42
 */
@RestController
@RequestMapping("gridNotice")
@Tag(name = "GridNoticeController", description = "网格公告相关管理相关api")
public class GridNoticeController extends BaseController {

    @DubboReference
    private GridNoticeService gridNoticeService;
    @DubboReference
    private GridNoticeRelationService gridNoticeRelationService;

    @DubboReference
    private SysGroupService sysGroupService;

    @DubboReference
    private SysGroupRegionService sysGroupRegionService;
    @DubboReference
    private VillageService villageService;
    @DubboReference
    private GridService gridService;

    @Autowired
    private GridHelper gridHelper;

    /**
     * 修改启用状态
     *
     * @param gridNoticeDto
     * @return
     */
    @PostMapping("updateStatus")
    @RequirePermissions(values = "gridNotice:edit")
    @Operation(summary = "修改单条网格公告状态")
    public Response<Object> updateStatus(@RequestBody GridNoticeDto gridNoticeDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(gridNoticeDto.getId()));
        if (gridNoticeService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        GridNoticeDto dbDto = gridNoticeService.selectById(gridNoticeDto.getId());
        dbDto.setStatus(gridNoticeDto.getStatus());
        //填充基础数据
        fillEditCommonData(dbDto);

        gridNoticeService.updateById(dbDto);

        return Response.ok();
    }


    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "gridNotice:list")
    @Operation(summary = "本级创建分页列表")
    public Response<Page<GridNoticeDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        //查询当前用户组级别
        List<GridRegionInfoDto> gridRegionInfoDtos = gridHelper.queryRegionInfoByGroupId(SessionHolder.getSysUser().getGroupId());

        if (CollectionUtils.isEmpty(gridRegionInfoDtos)) {
            Page<GridNoticeDto> page = new Page<>(request.getPageNo(), request.getPageSize(), 0, Collections.emptyList());
            return Response.<Page<GridNoticeDto>>ok().wrap(page);
        }

        List<String> creatorUniqueFlags = gridRegionInfoDtos.stream().map(GridRegionInfoDto::getCode).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(creatorUniqueFlags)) {
            request.put(LambdaUtil.getFieldName(GridNoticeDto::getCreatorLevel), gridRegionInfoDtos.get(0).getLevel());
            request.put(GridConstant.CREATOR_UNIQUE_FLAGS, creatorUniqueFlags);
        }

        int total = gridNoticeService.queryTotal(request.getParams());
        List<GridNoticeDto> list = null;
        if (total > 0) {
            list = gridNoticeService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<GridNoticeDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<GridNoticeDto>>ok().wrap(page);
    }


    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "gridNotice:edit")
    @Operation(summary = "查询单条网格公告记录")
    public Response<GridNoticeDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (gridNoticeService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        GridNoticeDto gridNoticeDto = gridNoticeService.selectById(id);

        if (CollectionUtils.isNotEmpty(gridNoticeDto.getRelationList())) {
            gridNoticeDto.getRelationList().forEach(gridNoticeRelationDto -> gridNoticeRelationDto.setGridRegionInfo(gridHelper.packRegionInfo(gridNoticeRelationDto.getSourceType(), gridNoticeRelationDto.getSourceId())));
        }

        return Response.<GridNoticeDto>ok().wrap(gridNoticeDto);
    }


    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "gridNotice:info")
    @Operation(summary = "查询单条记录")
    public Response<GridNoticeDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (gridNoticeService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        GridNoticeDto gridNoticeDto = gridNoticeService.selectById(id);

        if (CollectionUtils.isNotEmpty(gridNoticeDto.getRelationList())) {
            gridNoticeDto.getRelationList().forEach(gridNoticeRelationDto -> gridNoticeRelationDto.setGridRegionInfo(gridHelper.packRegionInfo(gridNoticeRelationDto.getSourceType(), gridNoticeRelationDto.getSourceId())));
        }


        return Response.<GridNoticeDto>ok().wrap(gridNoticeDto);
    }

    /**
     * 保存
     *
     * @param gridNoticeDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "gridNotice:edit")
    @Operation(summary = "保存单条网格公告记录")
    public Response<Object> save(@RequestBody @Validated GridNoticeDto gridNoticeDto) {

        if (CollectionUtils.isEmpty(gridNoticeDto.getRelationList())) {
            return Response.error("关联网格规则不能为空");
        }

        //填充基础数据
        fillSaveCommonData(gridNoticeDto);

        List<GridRegionInfoDto> gridRegionInfoDtos = gridHelper.queryRegionInfoByGroupId(SessionHolder.getSysUser().getGroupId());

        if (CollectionUtils.isEmpty(gridRegionInfoDtos)) {
            return Response.error("当前用户不支持创建通知公告");
        }

        //如果是社区级别,需要选择villageId
        if (GridConstant.RegionLevel.VILLAGE_LEVEL.getLevel().equals(gridRegionInfoDtos.get(0).getLevel()) && gridNoticeDto.getVillageId() == null) {
            return Response.error("需要指定小区");
        }
        //设置等级
        gridNoticeDto.setCreatorUniqueFlag(gridRegionInfoDtos.get(0).getCode());
        gridNoticeDto.setCreatorLevel(gridRegionInfoDtos.get(0).getLevel());

        if (Boolean.FALSE.equals(gridHelper.checkIfExistChildRegion(SessionHolder.getSysUser().getGroupId(), gridNoticeDto.getRelationList()))) {
            return Response.error("关联网格规则不合法");
        }

        gridNoticeService.saveOrUpdate(gridNoticeDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param gridNoticeDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "gridNotice:edit")
    @Operation(summary = "修改单条网格公告记录")
    public Response<Object> update(@RequestBody @Validated GridNoticeDto gridNoticeDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(gridNoticeDto.getId()));
        if (gridNoticeService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(gridNoticeDto);

        if (CollectionUtils.isEmpty(gridNoticeDto.getRelationList())) {
            return Response.error("关联网格规则不能为空");
        }

        //填充基础数据
        fillSaveCommonData(gridNoticeDto);

        List<GridRegionInfoDto> gridRegionInfoDtos = gridHelper.queryRegionInfoByGroupId(SessionHolder.getSysUser().getGroupId());

        if (CollectionUtils.isEmpty(gridRegionInfoDtos)) {
            return Response.error("当前用户不支持创建通知公告");
        }

        //如果是社区级别,需要选择villageId
        if (GridConstant.RegionLevel.VILLAGE_LEVEL.getLevel().equals(gridRegionInfoDtos.get(0).getLevel()) && gridNoticeDto.getVillageId() == null) {
            return Response.error("需要指定小区");
        }
        //设置等级
        gridNoticeDto.setCreatorUniqueFlag(gridRegionInfoDtos.get(0).getCode());
        gridNoticeDto.setCreatorLevel(gridRegionInfoDtos.get(0).getLevel());


        if (Boolean.FALSE.equals(gridHelper.checkIfExistChildRegion(SessionHolder.getSysUser().getGroupId(), gridNoticeDto.getRelationList()))) {
            return Response.error("关联网格规则不合法");
        }

        gridNoticeService.saveOrUpdate(gridNoticeDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "gridNotice:delete")
    @Operation(summary = "批量删除存在的网格公告记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (gridNoticeService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        gridNoticeService.deleteBatch(ids);

        return Response.ok();
    }
}
